package mssql

import "strings"

type Condition struct {
    whereSql	string
    args		[]interface{}
}

func (this *Condition) SetFilterEx(key string, ex string, val interface{}) error {
    sql := ""
    if strings.Index(key, "`") != -1 || strings.Index(key, ".") != -1 {
        sql += key
    } else {
        sql += "`" + key + "`"
    }
    args := []interface{}{}
    switch val.(type) {
    default:
        sql += " " + ex + " ?"
        args = append(args, val)
    case []interface{}:
        sql += " " + ex + " ("
        strAry := val.([]interface{})
        for i, v := range strAry {
            if i == 0 {
                sql += "?"
            } else {
                sql += ",?"
            }
            args = append(args, v)
        }
        sql += ")"
    case []string:
        sql += " in ("
        strAry := val.([]string)
        for i, v := range strAry {
            if i == 0 {
                sql += "?"
            } else {
                sql += ",?"
            }
            args = append(args, v)
        }
        sql += ")"
    case []int:
        sql += " in ("
        strAry := val.([]int)
        for i, v := range strAry {
            if i == 0 {
                sql += "?"
            } else {
                sql += ",?"
            }
            args = append(args, v)
        }
        sql += ")"
    case []int64:
        sql += " in ("
        strAry := val.([]int64)
        for i, v := range strAry {
            if i == 0 {
                sql += "?"
            } else {
                sql += ",?"
            }
            args = append(args, v)
        }
        sql += ")"
    case []float64:
        sql += " in ("
        strAry := val.([]float64)
        for i, v := range strAry {
            if i == 0 {
                sql += "?"
            } else {
                sql += ",?"
            }
            args = append(args, v)
        }
        sql += ")"
    }
    if len(this.whereSql) == 0 {
        this.whereSql = sql
    } else {
        this.whereSql += " and " + sql
    }
    if len(args) != 0 {
        this.args = append(this.args, args...)
    }
    return nil
}

// 设置搜索条件
// key 字段名称
// val 值, 如果是int或者string则表示等于; 如果是[]int 或者 []string 则表示in查询 其他类型不支持
func (this *Condition) SetFilter(key string, val interface{}) *Condition {
    this.SetFilterEx(key, "=", val)
    return this
}

func (this *Condition) SetFilterOr(conditions ...*Condition) {
    for _, condition := range conditions {
        sql, args := condition.GetSql()
        if len(this.whereSql) == 0 {
            this.whereSql = "(" + sql + ")"
        } else {
            this.whereSql += " or (" + sql + ")"
        }
        this.args = append(this.args, args...)
    }
}

func (this *Condition) GetSql() (string, []interface{}) {
    return this.whereSql, this.args
}
